<template>
  <a-modal title="图形验证" width="331px" v-model:visible="modalVisible" unmount-on-close :mask-closable="false">
    <!-- 图片验证码 -->
    <p class="text-tips" style="margin: 0 0 10px">请输入下方图片中的验证码</p>
    <div class="input-box">
      <input
        class="custom-input"
        type="text"
        v-model="vCode"
        placeholder="请输入"
        :class="{ 'custom-input-error': vCodeError }"
        @blur="vCodeBlur"
      />
      <div class="error-text" v-if="vCodeError">请输入图片验证码</div>
    </div>
    <div class="img-box" v-if="vCodeSrc">
      <img class="img-code" :src="vCodeSrc" />
      <div class="img-code-change" @click="getImgCodeSrc">看不清，换一张</div>
    </div>
    <template #footer>
      <a-button type="primary" long :loading="okLoading" @click="submit">确认</a-button>
    </template>
  </a-modal>
</template>

<script>
  import { Message } from '@arco-design/web-vue'
  import { login, sendSMSCode } from '@/api/user'
  export default {
    emits: ['success', 'changeIndex', 'security-verification'],
    data() {
      return {
        vCode: '',
        okLoading: false,
        vCodeError: false,
        modalVisible: false,
        vCodeSrc: '', // 图形验证码
        operateType: '',
      }
    },
    methods: {
      /** 开启弹窗
       * @param {*} codeParam 图形验证码入参 类似 { phone: ****, userName: *****, password: ***** } 中的一个或多个值
       * @param {*} operateType 事件类型：'securityVerify' 安全认证，'resetPassword' 重置密码
       */
      open(codeParam = {}, operateType) {
        this.codeParam = codeParam
        this.operateType = operateType
        this.modalVisible = true

        // 重置
        this.reset()
      },
      /**
       * 图形验证码失焦
       */
      vCodeBlur() {
        this.vCodeError = !this.vCode
      },
      /**
       * 重置
       */
      reset() {
        // 去除确认按钮loading
        this.okLoading = false
        // 去除无值提示
        this.vCodeError = false
        // 更新图片
        this.getImgCodeSrc()
      },
      /***
       * 将对象转化为固定字符串
       *
       */
      stringify(objs, sep = '&', ep = '=') {
        let str = ''
        Object.keys(objs).forEach((obj) => {
          str += obj + ep + objs[obj] + sep
        })
        return str.slice(0, -1)
      },
      /**
       * 获取图形验证码
       */
      getImgCodeSrc() {
        const param = {
          timeStamp: Date.now(),
        }
        if (this.codeParam.userName) param.userName = this.codeParam.userName
        if (this.codeParam.phone) param.phone = this.codeParam.phone
        this.vCodeSrc = `/api/saas/getValidateCode?` + this.stringify(param)
        // 去除 vCode
        this.vCode = ''
      },
      /**
       * 确定
       */
      submit() {
        if (!this.vCode) {
          Message.warning('请输入图形验证码')
          return
        }
        this.okLoading = true
        // 调用接口
        // 情况1：登录调用验证码，调用登录接口，传入 账号、密码、图形验证码
        if (this.operateType == 'login') {
          login({
            userName: this.codeParam.userName,
            password: this.codeParam.password,
            vCode: this.vCode,
          })
            .then((res) => {
              this.modalVisible = false
              const loginRes = res.result
              if (loginRes.status) {
                // 登录成功
                this.$emit('success', this.operateType)
              } else {
                // 此时有可能是需要打开安全验证
                const statusCode = loginRes.statusCode
                if (statusCode) {
                  // 需要安全验证
                  if (statusCode == 30) {
                    // 手机号后四位
                    const encryptionPhoneNumber = loginRes.message
                    this.$emit('security-verification', encryptionPhoneNumber)
                  }
                } else {
                  Message.warning('登录失败，' + loginRes.message)
                }
              }
              // 关闭弹窗
              this.modalVisible = false
            })
            .catch(() => {
              this.reset()
            })
            .finally(() => {
              this.okLoading = false
            })
        }
        // 情况2：安全认证-发送短信，传入 账号、图形验证码
        // 情况3：重置密码-发送短信，传入 手机号、图形验证码
        if (this.operateType == 'securityVerify' || this.operateType == 'resetPassword') {
          const param = {
            vCode: this.vCode,
          }
          if (this.operateType == 'securityVerify') {
            param.userName = this.codeParam.userName
          }
          if (this.operateType == 'resetPassword') {
            param.phone = this.codeParam.phone
          }
          sendSMSCode(param)
            .then((res) => {
              if (res.result.status) {
                Message.success(res.result.message)
                this.$emit('success')
              } else {
                Message.warning(res.result.message)
              }
              // 关闭弹窗
              this.modalVisible = false
            })
            .catch(() => {
              this.reset()
            })
            .finally(() => {
              this.okLoading = false
            })
        }
      },
    },
  }
</script>
<style lang="less" scoped>
  .input-box {
    .custom-input {
      width: 100%;
      height: 40px;
      font-size: 14px;
      border-radius: 3px;
      padding: 14px 0 14px 18px;
      border: 1px solid #c5c6cd;
      outline-style: none;
    }
    .custom-input:focus {
      outline: none;
      border: 1px solid #165dff;
    }
    .custom-input-error {
      outline: none;
      border: 1px solid #ff5b5a;
    }
    .error-text {
      height: 22px;
      font-size: 14px;
      font-family: PingFang SC-Regular, PingFang SC;
      font-weight: 400;
      color: #ff5b5a;
      line-height: 22px;
      margin-top: 12px;
    }
  }
  .img-box {
    display: flex;
    align-items: center;
    margin-top: 12px;
    .img-code {
      width: 144px;
      height: 40px;
      margin-left: 0;
      border: 1px solid #c5c6cd;
    }
    .img-code-change {
      height: 22px;
      line-height: 22px;
      font-size: 14px;
      color: #86909c;
      height: 22px;
      line-height: 22px;
      margin-left: 24px;
      cursor: pointer;
    }
  }
</style>
